package com.yinhe.music.yhmusic.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yinhe.music.type.person.BannerInfo;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.album.info.AlbumInfoActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.enums.BannerEnum;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.login.validcode.WebActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.radio.RadioActivity;
import com.yinhe.music.yhmusic.singer.info.SingerInfoActivity;
import com.yinhe.music.yhmusic.songmenu.SongMenuActivity;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.yinhe.music.common.utils.DisplayUtil.dip2px;


/**
 * 视图工具类
 * Created by hzwangchenyan on 2016/1/14.
 */

public class ViewUtils {

    public static ProgressDialog showWaitingDialog(Context context, String message, String title, boolean cancelable) {
        ProgressDialog waitingDialog = new ProgressDialog(context);
        if (title != null) {
            waitingDialog.setTitle(title);
        }
        if (message != null) {
            waitingDialog.setMessage(message);
        }
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(cancelable);
        return waitingDialog;
    }

    public static SpannableStringBuilder setStyleText(String text1, String text2, Context mContext, String color1, String color2, int size1, int size2, String change) {
        String title = String.format("%1$s" + change + "%2$s", text1, text2);
        int z = title.lastIndexOf(change);
        SpannableStringBuilder style = new SpannableStringBuilder(title);
        style.setSpan(new AbsoluteSizeSpan(dip2px(mContext, size1)), 0, text1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
        if (color1 != null) {
            style.setSpan(new ForegroundColorSpan(Color.parseColor(color1)), 0, text1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
        }
        if (color2 != null) {
            style.setSpan(new ForegroundColorSpan(Color.parseColor(color2)), z, title.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
        }
        style.setSpan(new AbsoluteSizeSpan(dip2px(mContext, size2)), z, title.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
        return style;
    }


    public static SpannableStringBuilder setCommentText(String text1, String text2, Context mContext, String color1, String color2, int size1, int size2) {
        String title = String.format("回复%1$s ：%2$s", text1, text2);
        int z = title.lastIndexOf("：");
        SpannableStringBuilder style = new SpannableStringBuilder(title);
        style.setSpan(new AbsoluteSizeSpan(dip2px(mContext, size1)), 2, text1.length() + 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
        if (color1 != null) {
            style.setSpan(new ForegroundColorSpan(Color.parseColor(color1)), 2, text1.length() + 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
        }
        if (color2 != null) {
            style.setSpan(new ForegroundColorSpan(Color.parseColor(color2)), z, title.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //颜色
        }
        style.setSpan(new AbsoluteSizeSpan(dip2px(mContext, size2)), z, title.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //字号
        return style;
    }

    public static void setBanner(Banner banner) {
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        Integer[] image = {
                R.drawable.ic_default_banner,
                R.drawable.ic_default_banner,
                R.drawable.ic_default_banner
        };
        List<Integer> defaultImages = new ArrayList<>();

        Collections.addAll(defaultImages, image);
        banner.setImages(defaultImages);
        //设置图片集合
        banner.setDelayTime(5000);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    private static class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            try {
                Glide.with(context).load(path).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void updateBanner(Banner banner, final List<BannerInfo> bannerInfos, final Context context) {
        List<String> images = new ArrayList<>();
        if (bannerInfos != null && !bannerInfos.isEmpty()) {
            for (int i = 0; i < bannerInfos.size(); i++) {
                images.add(bannerInfos.get(i).getImage());
            }
            banner.setOnBannerListener(position -> {
                switch (bannerInfos.get(position).getMessageType()) {
                    case BannerEnum.SINGER:
                        Intent intent = new Intent(context, SingerInfoActivity.class);
                        intent.putExtra("singerId", Integer.parseInt(bannerInfos.get(position).getMessageId()));
                        context.startActivity(intent);
                        break;
                    case BannerEnum.ALBUM:
                        Intent albumIntent = new Intent(context, AlbumInfoActivity.class);
                        albumIntent.putExtra("albumId", Integer.parseInt(bannerInfos.get(position).getMessageId()));
                        context.startActivity(albumIntent);
                        break;
                    case BannerEnum.MV:
                        break;
                    case BannerEnum.RADIO:
                        Intent radioIntent = new Intent(context, RadioActivity.class);
                        radioIntent.putExtra("radioid", Integer.parseInt(bannerInfos.get(position).getMessageId()));
                        context.startActivity(radioIntent);
                        break;
                    case BannerEnum.SONG:
                        Intent song = new Intent(context, SongMenuActivity.class);
                        song.putExtra("menuid", Integer.parseInt(bannerInfos.get(position).getMessageId()));
                        song.putExtra("type", Music.Type.ONLINE);
                        context.startActivity(song);
                        break;
                    case BannerEnum.OUTER_WEB:
                        //跳转网页
                        Intent webIntent = new Intent();
                        webIntent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(bannerInfos.get(position).getUrl());
                        webIntent.setData(content_url);
                        context.startActivity(webIntent);
                        break;
                    case BannerEnum.INNER_WEB:
                        Intent innerIntent = new Intent(context, WebActivity.class);
                        innerIntent.putExtra("url", bannerInfos.get(position).getUrl());
                        context.startActivity(innerIntent);
                        break;
                    default:
                        break;
                }
            });

            banner.update(images);
        }
    }

    public static void reflexIndicator(final TabLayout tabLayout, final int dp) {
        tabLayout.post(() -> {
            try {
                LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                int dp25 = dip2px(tabLayout.getContext(), dp);

                for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                    View tabView = mTabStrip.getChildAt(i);
                    Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                    mTextViewField.setAccessible(true);

                    TextView mTextView = (TextView) mTextViewField.get(tabView);

                    tabView.setPadding(0, 0, 0, 0);

                    int width = 0;
                    width = mTextView.getWidth();
                    if (width == 0) {
                        mTextView.measure(0, 0);
                        width = mTextView.getMeasuredWidth();
                    }

                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                    params.width = width;
                    params.leftMargin = dp25;
                    params.rightMargin = dp25;
                    tabView.setLayoutParams(params);
                    tabView.invalidate();
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    }

    /*
    * 获取支持软输入高度
    * */
    public static int getSupportSoftInputHeight(Activity activity) {
        Rect r = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();
        int softInputHeight = screenHeight - r.bottom;
        if (Build.VERSION.SDK_INT >= 20) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight(activity);
        }
        return softInputHeight;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static int getSoftButtonsBarHeight(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        return realHeight > usableHeight
                ? realHeight - usableHeight
                : 0;
    }
}
